package com.zy.mydemo.common.config;

import com.zy.mydemo.api.service.UserService;
import com.zy.mydemo.common.utils.PasswordUtils;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.LinkedHashMap;

/**
 * @Author:zhongyong
 * @Description：
 * @Date：Create in 2020/04/30
 */
@Configuration
public class shiroConfig {

    @Resource
    UserService userService;

    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);


        //配置过滤器,进行页面拦截
        /**
         * anon 无需认真
         * authc 必须认真
         * user 针对rememberMe功能访问
         * prems 资源权限才能访问
         * role 角色才能访问
         */
        shiroFilterFactoryBean.setFilterChainDefinitionMap(new LinkedHashMap<String, String>() {{
            //静态资源文件免验证
            put("/public/**", "anon");
            //登录登出动作免验证
            put("/api/user/doLogin", "anon");
            put("/api/user/doLogout", "anon");

            put("/**", "authc");

//            //二级目录下验证
//            put("/", "authc");
//            put("/*/**", "authc");

//            put("/api/user/**", "perms[user:get]");

        }});

        shiroFilterFactoryBean.setLoginUrl("/login");


        return shiroFilterFactoryBean;
    }

    @Bean(name = "securityManager")
    public DefaultWebSecurityManager securityManager(@Qualifier("userRealm") ShiroRealm shiroRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(shiroRealm);
        return securityManager;
    }

    @Bean(name = "userRealm")
    public ShiroRealm userRealm() {
        ShiroRealm shiroRealm = new ShiroRealm();

        //设置密码加密规则
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        hashedCredentialsMatcher.setHashAlgorithmName(PasswordUtils.HASH_ALGORITHM_NAME);
        hashedCredentialsMatcher.setHashIterations(PasswordUtils.HASH_ITERATIONS);
        hashedCredentialsMatcher.setStoredCredentialsHexEncoded(true);

        shiroRealm.setCredentialsMatcher(hashedCredentialsMatcher);
        return shiroRealm;
    }
}
